package com.jic.market.impl;

import com.jic.common.base.vo.AdminOperate;
import com.jic.common.utils.DateUtils;
import com.jic.common.utils.IDUtils;
import com.jic.market.common.util.BeanUtil;
import com.jic.market.entity.LargeTurntableTemplateEntity;
import com.jic.market.entity.LotteryTheme;
import com.jic.market.entity.LotteryType;
import com.jic.market.entity.Tag;
import com.jic.market.enums.FrontPromotionTypeEnum;
import com.jic.market.enums.PromotionStatusEnum;
import com.jic.market.enums.PromotionTypeEnum;
import com.jic.market.mapper.*;
import com.jic.market.request.MemberGradeInfoRequest;
import com.jic.market.request.PromotionMemberGradeRequest;
import com.jic.market.request.after.TellAddAllocationRequest;
import com.jic.market.request.manager.lottery.*;
import com.jic.market.response.manager.lottery.LotteryActivityResponse;
import com.jic.market.response.manager.lottery.LotteryAwardsResponse;
import com.jic.market.response.manager.lottery.LotteryThemeResponse;
import com.jic.market.service.LotteryActivityService;
import com.jic.market.service.PromotionMemberGradeService;
import com.jic.market.service.PromotionTemplateService;
import com.jic.market.service.allocation.AllocationLogicService;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 抽奖活动业务处理
 *
 * @author :
 * @version : v1.0.0
 * @email :
 * @since : 2020-03-03 03:06:48
 */
@Service
public class LotteryActivityServiceImpl implements LotteryActivityService {

    @Autowired
    private LotteryThemeMapper lotteryThemeMapper;

    @Autowired
    private LotteryAwardsMapper lotteryAwardsMapper;

    @Autowired
    private LotteryTypeMapper lotteryTypeMapper;

    @Autowired
    private PromotionTemplateService promotionTemplateService;

    @Autowired
    private AllocationLogicService allocationLogicService;

    @Autowired
    private PromotionMemberGradeService promotionMemberGradeService;

    @Autowired
    LargeTurntableTemplateEntityMapper largeTurntableTemplateEntityMapper;

    /**
     * 抽奖活动详情页查询
     *
     * @param request
     * @return
     */
    @Override
    public LotteryActivityResponse getLotteryActivityInfo(LotteryThemeRequest request) {
        LotteryActivityResponse lotteryActivityResponse = new LotteryActivityResponse();
        Long id = request.getId();
        LotteryTheme lotteryTheme = lotteryThemeMapper.queryById(id);
        LotteryType lotteryType = lotteryTypeMapper.queryByThemeRefId(id);
        List<LotteryAwardsResponse> lotteryAwardsList = lotteryAwardsMapper.queryByThemeRefId(id);

        lotteryActivityResponse = BeanUtil.copy(lotteryTheme, LotteryActivityResponse.class);
        if (null != lotteryType) {
            lotteryActivityResponse.setType(lotteryType.getType());
            lotteryActivityResponse.setTypeName(lotteryType.getTypeName());
            lotteryActivityResponse.setDrawPointsPerTime(lotteryType.getDrawPointsPerTime());
            lotteryActivityResponse.setDrawTimesPerOrder(lotteryType.getDrawTimesPerOrder());
            lotteryActivityResponse.setOrderDrawModel(lotteryType.getOrderDrawModel());
            lotteryActivityResponse.setOrderDrawType(lotteryType.getOrderDrawType());
            lotteryActivityResponse.setOrderDrawAmount(lotteryType.getOrderDrawAmount());
        }
        lotteryActivityResponse.setLotteryAwardsList(lotteryAwardsList);
        return lotteryActivityResponse;
    }

    /**
     * 保存抽奖-设置抽奖规则
     * 抽奖基础信息保存 @param lotteryTheme
     * 抽奖活动类型保存 @param lotteryType
     *
     * @param lotteryActivityRequest
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public long saveLotteryActivity(LotteryActivityRequest lotteryActivityRequest) {
        LotteryTheme lotteryTheme = BeanUtil.copy(lotteryActivityRequest, LotteryTheme.class);
        AdminOperate adminOperate = lotteryActivityRequest.getAdminOperate();
        lotteryTheme.setStatus(9);
        lotteryTheme.setFrontPromotionType(13);
        lotteryTheme.setCreator(adminOperate.getOperator());
        lotteryTheme.setCreatorName(adminOperate.getOperateName());
        lotteryTheme.setDeptId(adminOperate.getDeptId());
        lotteryTheme.setPromotionCode(IDUtils.GenerateBillNo());
        lotteryTheme.setDeptType(adminOperate.getDeptType().getCode());
        Long aLong = lotteryThemeMapper.insert(lotteryTheme);
        long id = lotteryTheme.getId();
        LotteryType lotteryType = new LotteryType();
        lotteryType.setThemeRefId(id);
        lotteryType.setType(lotteryTheme.getLotteryType());
        lotteryType.setDeptId(adminOperate.getDeptId());
        lotteryType.setCreator(adminOperate.getOperator());
        lotteryType.setCreatorName(adminOperate.getOperateName());
        if (lotteryTheme.getLotteryType() == 1) {
            lotteryType.setTypeName("无订单抽奖");
            lotteryType.setCostFreeDrawTimes(lotteryActivityRequest.getCostFreeDrawTimes());
            lotteryType.setDrawPointsPerTime(lotteryActivityRequest.getDrawPointsPerTime());

        }
        //抽奖活动类型 订单抽奖
        if (lotteryTheme.getLotteryType() == 2) {
            lotteryType.setTypeName("订单抽奖");
            lotteryType.setDrawTimesPerOrder(lotteryActivityRequest.getDrawTimesPerOrder());
            lotteryType.setOrderDrawModel(lotteryActivityRequest.getOrderDrawModel());
            lotteryType.setOrderDrawType(lotteryActivityRequest.getOrderDrawType());
            lotteryType.setOrderDrawAmount(lotteryActivityRequest.getOrderDrawAmount());
        }
        lotteryTypeMapper.insert(lotteryType);
        return id;
    }

    /**
     * 保存抽奖活动-奖项设置
     *
     * @param lotteryAwardsListRequest
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer saveLotteryAwards(LotteryAwardsListRequest lotteryAwardsListRequest) {
        if (lotteryAwardsListRequest.getLotteryAwardsList() != null && lotteryAwardsListRequest.getLotteryAwardsList().size() > 0) {
            List<LotteryAwardsRequest> list = lotteryAwardsListRequest.getLotteryAwardsList();
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i) != null) {
                    list.get(i).setThemeRefId(lotteryAwardsListRequest.getThemeRefId());
                    list.get(i).setDeptid(lotteryAwardsListRequest.getAdminOperate().getDeptId());
                    list.get(i).setCreator(lotteryAwardsListRequest.getAdminOperate().getOperator());
                    list.get(i).setCreatorName(lotteryAwardsListRequest.getAdminOperate().getOperateName());
                }
            }
            lotteryAwardsMapper.foreachInsert(list);
        }
        //未中奖说明保存
        LotteryThemeRequest lotteryThemeRequest = new LotteryThemeRequest();
        lotteryThemeRequest.setNotWinningDesc(lotteryAwardsListRequest.getNotWinningDesc());
        lotteryThemeRequest.setId(lotteryAwardsListRequest.getThemeRefId());
        lotteryThemeRequest.setUpdater(lotteryAwardsListRequest.getAdminOperate().getOperator());
        lotteryThemeRequest.setUpdaterName(lotteryAwardsListRequest.getAdminOperate().getOperateName());
        lotteryThemeRequest.setStatus(1);
        lotteryThemeRequest.setPageTemplateId(lotteryAwardsListRequest.getPageTemplateId());
        lotteryThemeRequest.setActivityRule(lotteryAwardsListRequest.getActivityRule());
        lotteryThemeRequest.setLaunchChannels(lotteryAwardsListRequest.getLaunchChannels());
        lotteryThemeRequest.setAndroidLink(lotteryAwardsListRequest.getAndroidLink());
        lotteryThemeRequest.setIosLink(lotteryAwardsListRequest.getIosLink());
        lotteryThemeRequest.setH5Link(lotteryAwardsListRequest.getH5Link());
        if(null != lotteryAwardsListRequest.getPageTemplateId()){
            LargeTurntableTemplateEntity largeTurntableTemplateEntity = largeTurntableTemplateEntityMapper.queryById(lotteryAwardsListRequest.getPageTemplateId());
            lotteryThemeRequest.setPageDescJson(null == largeTurntableTemplateEntity ? null : largeTurntableTemplateEntity.getDescJson());
        }
        lotteryThemeMapper.update(lotteryThemeRequest);
        return lotteryThemeRequest.getStatus();
    }

    /**
     * 编辑抽奖活动-抽奖规则
     *
     * @param lotteryActivityRequest
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public long updateLotteryActivity(LotteryActivityRequest lotteryActivityRequest) {
        LotteryThemeRequest lotteryThemeRequest = BeanUtil.copy(lotteryActivityRequest, LotteryThemeRequest.class);
        LotteryTheme lotteryTheme = lotteryThemeMapper.queryByPrimaryKey(lotteryThemeRequest.getId());
        AdminOperate adminOperate = lotteryActivityRequest.getAdminOperate();
        if (lotteryTheme.getStatus() == 9) {
            lotteryThemeRequest.setStatus(9);
        } else {
            lotteryThemeRequest.setStatus(1);
        }
        lotteryThemeMapper.update(lotteryThemeRequest);
        long id = lotteryThemeRequest.getId();
        LotteryType lotteryType = new LotteryType();
        lotteryType.setThemeRefId(id);
        lotteryType.setType(lotteryThemeRequest.getLotteryType());
        lotteryType.setDeptId(adminOperate.getDeptId());
        lotteryType.setUpdater(adminOperate.getOperator());
        lotteryType.setUpdaterName(adminOperate.getOperateName());
        if (lotteryThemeRequest.getLotteryType() == 1) {
            lotteryType.setTypeName("无订单抽奖");
            lotteryType.setCostFreeDrawTimes(lotteryActivityRequest.getCostFreeDrawTimes());
            lotteryType.setDrawPointsPerTime(lotteryActivityRequest.getDrawPointsPerTime());

        }
        //抽奖活动类型 订单抽奖
        if (lotteryThemeRequest.getLotteryType() == 2) {
            lotteryType.setTypeName("订单抽奖");
            lotteryType.setDrawTimesPerOrder(lotteryActivityRequest.getDrawTimesPerOrder());
            lotteryType.setOrderDrawModel(lotteryActivityRequest.getOrderDrawModel());
            lotteryType.setOrderDrawType(lotteryActivityRequest.getOrderDrawType());
            lotteryType.setOrderDrawAmount(lotteryActivityRequest.getOrderDrawAmount());
        }
        lotteryTypeMapper.updateThemeRefId(lotteryType);
        return id;
    }


    /**
     * 编辑抽奖活动-奖项设置
     *
     * @param lotteryAwardsListRequest
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer updateLotteryAwards(@RequestBody LotteryAwardsListRequest lotteryAwardsListRequest) {
        if (lotteryAwardsListRequest.getLotteryAwardsList() != null && lotteryAwardsListRequest.getLotteryAwardsList().size() > 0) {
            List<LotteryAwardsRequest> list = lotteryAwardsListRequest.getLotteryAwardsList();
            List<LotteryAwardsRequest> insetList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i) != null) {
                    list.get(i).setThemeRefId(lotteryAwardsListRequest.getThemeRefId());
                    list.get(i).setDeptid(lotteryAwardsListRequest.getAdminOperate().getDeptId());
                    list.get(i).setCreator(lotteryAwardsListRequest.getAdminOperate().getOperator());
                    list.get(i).setCreatorName(lotteryAwardsListRequest.getAdminOperate().getOperateName());
                    if(list.get(i).getId()!=null){
                        lotteryAwardsMapper.updateThemeRefId(list.get(i));
                    }else{
                        insetList.add(list.get(i));
                    }
                }
            }
            //编辑活动新增奖项
            if(insetList.size()>0){
                lotteryAwardsMapper.foreachInsert(insetList);
            }
//            lotteryAwardsMapper.updateThemeRefId(list);
        }
        //未中奖说明保存
        LotteryThemeRequest lotteryThemeRequest = new LotteryThemeRequest();
        lotteryThemeRequest.setNotWinningDesc(lotteryAwardsListRequest.getNotWinningDesc());
        lotteryThemeRequest.setId(lotteryAwardsListRequest.getThemeRefId());
        lotteryThemeRequest.setUpdater(lotteryAwardsListRequest.getAdminOperate().getOperator());
        lotteryThemeRequest.setUpdaterName(lotteryAwardsListRequest.getAdminOperate().getOperateName());
        lotteryThemeRequest.setStatus(1);
        lotteryThemeRequest.setPageTemplateId(lotteryAwardsListRequest.getPageTemplateId());
        lotteryThemeRequest.setActivityRule(lotteryAwardsListRequest.getActivityRule());
        lotteryThemeRequest.setLaunchChannels(lotteryAwardsListRequest.getLaunchChannels());
        lotteryThemeRequest.setAndroidLink(lotteryAwardsListRequest.getAndroidLink());
        lotteryThemeRequest.setIosLink(lotteryAwardsListRequest.getIosLink());
        lotteryThemeRequest.setH5Link(lotteryAwardsListRequest.getH5Link());
        if(null != lotteryAwardsListRequest.getPageTemplateId()){
            LargeTurntableTemplateEntity largeTurntableTemplateEntity = largeTurntableTemplateEntityMapper.queryById(Long.valueOf(lotteryAwardsListRequest.getPageTemplateId()));
            lotteryThemeRequest.setPageDescJson(null==largeTurntableTemplateEntity?null:largeTurntableTemplateEntity.getDescJson());
        }
        lotteryThemeMapper.update(lotteryThemeRequest);
        return lotteryThemeRequest.getStatus();
    }

    /**
     * 复制抽奖活动
     *
     * @param lotteryActivityRequest
     * @return
     */
    @Override
    public long copyLotteryActivity(LotteryActivityRequest lotteryActivityRequest) {
        //根据id获取抽奖及关联表数据
        AdminOperate adminOperate = lotteryActivityRequest.getAdminOperate();
        //主要信息
        LotteryTheme lotteryTheme = lotteryThemeMapper.queryByPrimaryKey(lotteryActivityRequest.getId());
        //活动规则
        LotteryType lotteryType = lotteryTypeMapper.queryByThemeRefId(lotteryActivityRequest.getId());
        //奖品设置
        List<LotteryAwardsResponse> lotteryAwardsResponse = lotteryAwardsMapper.queryByThemeRefId(lotteryActivityRequest.getId());
        List<LotteryAwardsRequest> lotteryAwards = BeanUtil.copy(lotteryAwardsResponse, LotteryAwardsRequest.class);
        lotteryTheme.setActivityName(lotteryTheme.getActivityName() + "-复制");
        lotteryTheme.setCreator(adminOperate.getOperator());
        lotteryTheme.setCreatorName(adminOperate.getOperateName());
        //复制活动 状态默认为待提交
        lotteryTheme.setStatus(PromotionStatusEnum.DRAFT.getCode());

        String oldPromotionCode = lotteryTheme.getPromotionCode();

        lotteryTheme.setPromotionCode(IDUtils.GenerateBillNo());
        lotteryTheme.setDeptType(adminOperate.getDeptType().getCode());
        long lotteryThemeId = lotteryThemeMapper.insert(lotteryTheme);
        long id = lotteryTheme.getId();
        if (lotteryType != null) {
            lotteryType.setThemeRefId(id);
            lotteryTypeMapper.insert(lotteryType);
        }
        if (lotteryType != null) {
            for (int i = 0; i < lotteryAwards.size(); i++) {
                if (lotteryAwards.get(i) != null) {
                    lotteryAwards.get(i).setThemeRefId(id);
                }
            }
            if (lotteryAwards.size() != 0) {
                lotteryAwardsMapper.foreachInsert(lotteryAwards);
            }
        }

        promotionMemberGradeService.copyMemberGrade(oldPromotionCode, lotteryTheme.getId().toString(), lotteryTheme.getPromotionCode());

        return id;
    }

    /**
     * 保存抽奖模板
     *
     * @param lotteryTemplateRequest
     * @return
     */
    @Override
    public Long saveTemplate(LotteryTemplateRequest lotteryTemplateRequest) {
        Long templateId = promotionTemplateService.saveTemplate(() -> {
            // 复制配置信息
            PromotionTemplateService.CopyResult copyResult = copyLotteryTemplate(lotteryTemplateRequest, PromotionStatusEnum.TEMPLATE, "-模板");
            copyResult.setAdminOperate(lotteryTemplateRequest.getAdminOperate());

            return copyResult;
        });
        return templateId;
    }

    /**
     * 创建模板数据
     *
     * @param lotteryTemplateRequest
     * @param status
     * @param extenPromName
     * @return
     */
    private PromotionTemplateService.CopyResult copyLotteryTemplate(LotteryTemplateRequest lotteryTemplateRequest, PromotionStatusEnum status, String extenPromName) {
        //根据id获取抽奖及关联表数据
        //主要信息
        LotteryTheme lotteryTheme = lotteryThemeMapper.queryByPrimaryKey(lotteryTemplateRequest.getId());
        //活动规则
        LotteryType lotteryType = lotteryTypeMapper.queryByThemeRefId(lotteryTemplateRequest.getId());
        //奖品设置
        List<LotteryAwardsResponse> lotteryAwardsResponse = lotteryAwardsMapper.queryByThemeRefId(lotteryTemplateRequest.getId());
        List<LotteryAwardsRequest> lotteryAwards = BeanUtil.copy(lotteryAwardsResponse, LotteryAwardsRequest.class);
        lotteryTheme.setActivityName(lotteryTheme.getActivityName() + "-模板");
        lotteryTheme.setCreator(lotteryTheme.getCreator());
        lotteryTheme.setCreatorName(lotteryTheme.getCreatorName());
        lotteryTheme.setFrontPromotionType(13);
        //复制活动 状态默认为待提交
        lotteryTheme.setStatus(10);

        lotteryTheme.setPromotionCode(IDUtils.GenerateBillNo());
        long lotteryThemeId = lotteryThemeMapper.insert(lotteryTheme);
        long id = lotteryTheme.getId();

        if (lotteryType != null) {
            lotteryType.setThemeRefId(id);
            lotteryTypeMapper.insert(lotteryType);
        }
        if (lotteryType != null) {
            for (int i = 0; i < lotteryAwards.size(); i++) {
                if (lotteryAwards.get(i) != null) {
                    lotteryAwards.get(i).setThemeRefId(id);
                }
            }
            if (lotteryAwards.size() != 0) {
                lotteryAwardsMapper.foreachInsert(lotteryAwards);
            }
        }
        //结果组装
        PromotionTemplateService.CopyResult copyResult = new PromotionTemplateService.CopyResult();
        copyResult.setPromotionId(Long.toString(id));
        copyResult.setPromType(PromotionTypeEnum.getByCode(13));
        copyResult.setTemplateName(lotteryTemplateRequest.getTemplateName() + extenPromName);
        return copyResult;

    }

    /**
     * 删除抽奖活动及关联数据
     *
     * @param lotteryActivityRequest
     * @return
     */
    @Override
    public void deleteLotteryActivity(LotteryActivityRequest lotteryActivityRequest) {
        lotteryThemeMapper.delete(lotteryActivityRequest.getId());
        lotteryTypeMapper.deleteByThemeRefId(lotteryActivityRequest.getId());
        lotteryAwardsMapper.deleteThemeRefId(lotteryActivityRequest.getId());
    }


    /**
     * 审核抽奖活动
     *
     * @param lotteryThemeRequest
     * @return
     */
    @Override
    public void verifyLotteryActivity(LotteryThemeRequest lotteryThemeRequest) {
        LotteryTheme lotteryTheme = lotteryThemeMapper.queryByPrimaryKey(lotteryThemeRequest.getId());
        LotteryThemeRequest param = new LotteryThemeRequest();
        //审核是否通过 通过为1 不通过为2
        if (lotteryThemeRequest.getVerifyStatus() == 1) {
            param.setStatus(lotteryThemeRequest.getVerifyStatus());
            //分摊
            TellAddAllocationRequest tellAddAllocationRequest = new TellAddAllocationRequest();
            tellAddAllocationRequest.setPromotionId(lotteryTheme.getId().toString());
            tellAddAllocationRequest.setPromType(lotteryTheme.getFrontPromotionType());
            allocationLogicService.addAllocation(tellAddAllocationRequest);
        } else {
            param.setStatus(lotteryThemeRequest.getVerifyStatus());
        }
        param.setUpdaterName(lotteryThemeRequest.getUpdaterName());
        param.setUpdater(lotteryThemeRequest.getUpdater());
        param.setAuditRemark(lotteryThemeRequest.getAuditRemark());
        param.setId(lotteryThemeRequest.getId());
        lotteryThemeMapper.updateStatus(param);
    }

    @Override
    public LotteryTheme queryByPrimaryKey(Long id) {
        LotteryTheme lotteryTheme = lotteryThemeMapper.queryByPrimaryKey(id);
        return lotteryTheme;
    }

    @Override
    public LotteryTheme queryByPromotionCode(String promotionCode) {
//        LotteryTheme lotteryTheme = lotteryThemeMapper.queryByPromotionCode(promotionCode);
//        return lotteryTheme;
        return  null;
    }

    public static void main(String[] args) {
//        String beginTime=new String("2018-10-20 11:22:22");
//        String endTime=new String("2017-06-09 10:22:22");
//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        try {
//            Date sd1=df.parse(beginTime);
//            Date sd2=df.parse(endTime);
//            long a = DateUtils.getSecondDiff(sd1,sd2);
//            System.out.println(a);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }

        System.out.println(PromotionTypeEnum.getByCode(13));
    }
}
